package com.campus.campusdelivery.service.impl;

import com.campus.campusdelivery.dto.ChangePasswordRequest;
import com.campus.campusdelivery.dto.UserProfileDto;
import com.campus.campusdelivery.entity.User;
import com.campus.campusdelivery.repository.UserRepository;
import com.campus.campusdelivery.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional
public class UserServiceImpl implements UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    @Override
    public UserProfileDto getUserProfile(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        UserProfileDto profileDto = new UserProfileDto();
        profileDto.setId(user.getId());
        profileDto.setUsername(user.getUsername());
        profileDto.setRealName(user.getRealName());
        profileDto.setPhone(user.getPhone());
        profileDto.setEmail(user.getEmail());
        profileDto.setAvatar(user.getAvatar());
        profileDto.setRole(user.getRole().toString());
        profileDto.setEnabled(user.getEnabled());
        
        return profileDto;
    }
    
    @Override
    public void updateUserProfile(Long userId, UserProfileDto profileDto) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 检查手机号是否被其他用户使用
        if (profileDto.getPhone() != null && !profileDto.getPhone().equals(user.getPhone())) {
            if (userRepository.existsByPhone(profileDto.getPhone())) {
                throw new RuntimeException("手机号已被使用");
            }
        }
        
        // 检查邮箱是否被其他用户使用
        if (profileDto.getEmail() != null && !profileDto.getEmail().equals(user.getEmail())) {
            if (userRepository.existsByEmail(profileDto.getEmail())) {
                throw new RuntimeException("邮箱已被使用");
            }
        }
        
        user.setRealName(profileDto.getRealName());
        user.setPhone(profileDto.getPhone());
        user.setEmail(profileDto.getEmail());
        user.setAvatar(profileDto.getAvatar());
        
        userRepository.save(user);
    }
    
    @Override
    public void changePassword(Long userId, ChangePasswordRequest request) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 验证当前密码
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            throw new RuntimeException("当前密码错误");
        }
        
        // 设置新密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userRepository.save(user);
    }
    
    @Override
    public void deleteAccount(Long userId, String password) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        // 删除用户（这里可以改为逻辑删除，将enabled设为false）
        user.setEnabled(false);
        userRepository.save(user);
    }
}